package crawlers;

import java.util.ArrayList;

import models.Software;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.Text;

import debug.SoftwareDebug;

public class CrawlerItuneXML {
	public static ArrayList<Software> getXML(String url)
	{
		ArrayList<Software> softwares = new ArrayList<Software>();
		try {
			Document doc = Jsoup.connect(url).get();
			String html = doc.html();
			html = html.replace("im:image", "artworkUrl")
					   .replace("im:name", "trackName")
					   .replace("im:price", "price")
					   .replace("im:artist", "artist");
			doc = Jsoup.parse(html);
			Software software = null;
			Elements entry = null;
			
			if (doc.select("entry").size() > 0) {
				for (int i = 0; i< doc.select("entry").size(); i++) {
					software = new Software();
					entry = (Elements) doc.select("entry").eq(i);
					//software.setUpdated(new Calendar(entry.select("updated").html()));
					//Set trackId
					software.setTrackId(Integer.parseInt(entry.select("id").attr("im:id")));
					//Set trackName
					software.setTrackName(entry.select("trackname").html());
					//Set trackViewURl
					software.setTrackViewUrl(entry.select("id").html());
					//Set artistName
					software.setArtistName(entry.select("artist").html());
					//Set description
					software.setDescription(new Text(entry.select("summary").html()));
					//Set bundleId
					software.setBundleId(entry.select("id").attr("im:bundleId"));
					//Set artistViewUrl
					software.setArtistViewUrl(entry.select("artist").attr("href"));
					//Set artworkUrl60
					software.setArtworkUrl60(entry.select("artworkurl").get(0).html());
					//Set artworkUrl100
					software.setArtworkUrl100(entry.select("artworkurl").get(1).html());
					//Set artworkUrl512
					software.setArtworkUrl512(entry.select("artworkurl").get(2).html());
					//Set category
					software.setCategory(entry.select("category").attr("term"));
					//Set price
					software.setPrice(new Float(entry.select("price").attr("amount")));
					softwares.add(software);
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return softwares;
	}
	
	public static void main(String[] args) {
		ArrayList<Software> softwares = new ArrayList<Software>();
		softwares = CrawlerItuneXML.getXML("http://itunes.apple.com/us/rss/topfreeapplications/limit=100/xml");
		if (softwares.size() > 0) {
			SoftwareDebug.debug(softwares.get(0));
		}
	}
}
